import { useEffect, useState } from 'react';
import { getMenuTree } from '@/services/menu';
import type { TreeProps } from 'antd';
import { Modal, Tree } from 'antd';
import { getRoleAuthInfo } from '@/services/roles';

interface IProps {
  actionType: 'detail' | 'auth';
  onFinished?: (ids: string[]) => Promise<boolean>;
  triggerEl: React.ReactNode;
  roleId: string;
}
const AuthRoleModal: React.FC<IProps> = ({ actionType, onFinished, triggerEl, roleId }) => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [treeData, setTreeData] = useState<MENU.MenuType[]>([]);
  const [checkedMenuKeys, setCheckedMenuKeys] = useState<string[]>([]);
  const loadMenuTree = () => {
    getMenuTree().then((res) => {
      if (res.success) {
        setTreeData(res.data);
      }
    });
  };

  const loadRoleAuthInfo = (id: string) => {
    getRoleAuthInfo({ id }).then((res) => {
      if (res.success) {
        setCheckedMenuKeys(res.data);
      }
    });
  };

  useEffect(() => {
    loadMenuTree();
  }, []);

  useEffect(() => {
    if (modalVisible) loadRoleAuthInfo(roleId);
  }, [modalVisible]);

  const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
    // console.log('onCheck', checkedKeys, info);
    setCheckedMenuKeys(checkedKeys as string[]);
  };

  const onFinish = async (ids: string[]) => {
    onFinished?.(ids).then((res) => {
      if (res) setModalVisible(false);
    });
  };

  return (
    <div>
      <div
        onClick={() => {
          setModalVisible(true);
        }}
      >
        {triggerEl}
      </div>
      <Modal
        open={modalVisible}
        width={520}
        footer={actionType === 'detail' ? null : undefined}
        title={actionType === 'detail' ? '角色授权信息' : '角色授权'}
        onCancel={() => {
          setModalVisible(false);
        }}
        okButtonProps={{
          disabled: checkedMenuKeys.length === 0,
        }}
        onOk={() => {
          onFinish(checkedMenuKeys);
        }}
      >
        <Tree
          disabled={actionType === 'detail'}
          checkable
          defaultExpandedKeys={treeData.map((item) => item.id)}
          checkedKeys={checkedMenuKeys}
          onCheck={onCheck}
          treeData={treeData}
          fieldNames={{ title: 'menuName', key: 'id' }}
        />
      </Modal>
    </div>
  );
};

export default AuthRoleModal;
